package network;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Created by Glogo on 2014/8/30.
 * 测试Socket的半关闭状态
 *
 * 与Reciever类对应
 */
public class Sender {

    private int port = 8000;
    private String host = "localhost";
    private Socket socket;

    public static int stopWay = 1;    //结束通信的方式
    private final int NATURAL_STOP = 1; //自然结束
    private final int SUDDEN_STOP  = 2; //突然终止程序
    private final int SOCKET_STOP  = 3; //关闭Socket，再结束程序
    private final int OUTPUT_STOP  = 4; //先关闭输出流，再结束程序

    public Sender() throws IOException {
        socket = new Socket(host, port);
    }


    private PrintWriter getWriter(Socket socket) throws IOException {
        OutputStream bos = socket.getOutputStream();
        return new PrintWriter(new OutputStreamWriter(bos), true);
    }

    public void send() throws Exception {
        PrintWriter pw = getWriter(socket);
        for(int i = 0; i < 20; i++){
            String msg = "hello_" + i;
            pw.println(msg);
            System.out.println("send:" + msg);
            Thread.sleep(1000);
            //下面这些都是未发送完就关闭
            if(i == 2){
                if (stopWay == SUDDEN_STOP){
                    System.out.println("突然终止程序");
                    System.exit(0);
                }else if (stopWay == SOCKET_STOP){
                    System.out.println("关闭Socket并终止程序");
                    socket.close();
                    break;
                }else if (stopWay == OUTPUT_STOP){
                    System.out.println("关闭输出流");
                    socket.shutdownOutput();
                    break;
                }
            }
        }
        //发送完成，正常关闭
        if(stopWay == NATURAL_STOP){
            socket.close();
        }
    }

    public static void main(String[] args) throws Exception {
        if(args.length > 0)
            stopWay = Integer.parseInt(args[0]);
        new Sender().send();
    }

}
